const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { UnauthorizedError } = require('../utils/error');
const { success, failure } = require('../utils/responses');


module.exports = async (req, res, next) => {
    try {
       const { token } = req.headers;
       if (!token) {
           throw new UnauthorizedError('当前接口需要认证才能访问');
       }

       const decoded = jwt.verify(token, process.env.SECRET);//验证token是否正确

    //  从jwt中解析出之前存入的userId
       const userId = decoded.id;
    //    查询一下，当前用户

       const user = await User.findByPk(userId);
 
       if(!user) {
           throw new UnauthorizedError('用户不存在');
       }

       if(user.role !== 100) {
           throw new UnauthorizedError('当前接口需要管理员权限才能访问')
       }
    //    登录的用户信息
       req.user = user;
       next();
    } catch (err) {
        failure(res, err);
    }
}